package com.bf.electroplating.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.ComWorkshopMapper;
import com.bf.electroplating.mapper.ComCompanyMapper;
import com.bf.electroplating.pojo.dto.workshop.ComWorkshopDTO;
import com.bf.electroplating.pojo.entity.ComWorkshop;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.PubAttachmentRel;
import com.bf.electroplating.pojo.entity.PubDataHistory;
import com.bf.electroplating.pojo.enums.AttModuleEnums;
import com.bf.electroplating.pojo.enums.PubDataHistoryTypeEnum;
import com.bf.electroplating.pojo.vo.workshop.ComWorkshopVO;
import com.bf.electroplating.service.ComWorkshopService;
import com.bf.electroplating.service.PubAttachmentRelService;
import com.bf.electroplating.service.PubAttachmentService;
import com.bf.electroplating.service.PubDataHistoryService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 15451
* @description 针对表【com_workshop(车间信息表)】的数据库操作Service实现
* @createDate 2025-05-09 11:11:32
*/
@Service
public class ComWorkshopServiceImpl extends ServiceImpl<ComWorkshopMapper, ComWorkshop>
    implements ComWorkshopService {

    @Resource
    private ComCompanyMapper companyMapper;
    @Resource
    private PubAttachmentService attachmentService;
    @Resource
    private PubDataHistoryService dataHistoryService;
    @Resource
    private PubAttachmentRelService attachmentRelService;

    @Override
    public Page<ComWorkshopVO> getWorkshopList(ComWorkshopDTO dto) {
        if (!StringUtils.isEmpty(dto.getCompanyName())) {
            dto.setCompanyId(dto.getCompanyName());
        }
        // 先查询所有符合条件的车间（按是否有关联镀槽排序）
        List<ComWorkshop> allWorkshops = baseMapper.selectWorkshopListWithTankSort(
                dto.getWorkshopName(), 
                dto.getWorkshopNumber(), 
                dto.getCompanyId()
        );
        
        // 手动分页
        int total = allWorkshops.size();
        int start = (dto.getPageNum() - 1) * dto.getPageSize();
        int end = Math.min(start + dto.getPageSize(), total);
        
        List<ComWorkshop> workshopPage = allWorkshops.subList(start, end);
        
        // 创建分页结果
        Page<ComWorkshopVO> voPage = new Page<>();
        voPage.setCurrent(dto.getPageNum());
        voPage.setSize(dto.getPageSize());
        voPage.setTotal(total);
        voPage.setPages((total + dto.getPageSize() - 1) / dto.getPageSize());

        // 获取所有涉及的企业ID
        List<String> companyIds = workshopPage.stream()
                .map(ComWorkshop::getCompanyId)
                .filter(StringUtils::hasText)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询企业信息
        Map<String, String> companyNameMap = new HashMap<>();
        if (!companyIds.isEmpty()) {
            LambdaQueryWrapper<ComCompany> companyWrapper = new LambdaQueryWrapper<>();
            companyWrapper.in(ComCompany::getId, companyIds);
            List<ComCompany> companies = companyMapper.selectList(companyWrapper);
            companyNameMap = companies.stream()
                    .collect(Collectors.toMap(ComCompany::getId, ComCompany::getCompanyName, (k1, k2) -> k1));
        }

        // 封装VO对象
        Map<String, String> finalCompanyNameMap = companyNameMap;
        List<ComWorkshopVO> voList = workshopPage.stream().map(workshop -> {
            ComWorkshopVO vo = new ComWorkshopVO();
            BeanUtils.copyProperties(workshop, vo);
            vo.setProductionLineConstructionT(getDateStr(workshop.getProductionLineConstructionT()));
            // 设置企业名称
            if (StringUtils.hasText(workshop.getCompanyId())) {
                vo.setCompanyName(finalCompanyNameMap.getOrDefault(workshop.getCompanyId(), ""));
            }
            vo.setAttachmentIds(attachmentService.getWholeFile(workshop.getId(), AttModuleEnums.WORKSHOP.getCode()));
            vo.setFloorPlan (attachmentService.getOneFile (workshop.getId(), AttModuleEnums.FLOOR_PLAN.getCode()));
            vo.setScene (attachmentService.getOneFile(workshop.getId(), AttModuleEnums.SCENE.getCode()));
            vo.setEiaChapter (attachmentService.getOneFile(workshop.getId(), AttModuleEnums.EIA_CHAPTER.getCode()));

            return vo;
        }).collect(Collectors.toList());

        voPage.setRecords(voList);
        return voPage;
    }

    private String getDateStr(Date date) {
        if ( ObjectUtils.isEmpty ( date ) ) {
            return null;
        }
        LocalDate localDate = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return formatter.format(localDate);
    }

    @Override
    public ComWorkshopVO getWorkshopById(String id) {
        ComWorkshop workshop = this.getById(id);
        if (workshop == null) {
            return null;
        }
        
        ComWorkshopVO vo = new ComWorkshopVO();
        BeanUtils.copyProperties(workshop, vo);
        vo.setProductionLineConstructionT(getDateStr(workshop.getProductionLineConstructionT()));
        // 查询企业名称
        if (StringUtils.hasText(workshop.getCompanyId())) {
            ComCompany company = companyMapper.selectById(workshop.getCompanyId());
            if (company != null) {
                vo.setCompanyName(company.getCompanyName());
            }
            vo.setAttachmentIds(attachmentService.getWholeFile(workshop.getId(), AttModuleEnums.WORKSHOP.getCode()));
            vo.setFloorPlan (attachmentService.getOneFile (workshop.getId(), AttModuleEnums.FLOOR_PLAN.getCode()));
            vo.setScene (attachmentService.getOneFile(workshop.getId(), AttModuleEnums.SCENE.getCode()));
            vo.setEiaChapter (attachmentService.getOneFile(workshop.getId(), AttModuleEnums.EIA_CHAPTER.getCode()));
        }
        
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveWorkshop(ComWorkshopVO vo) {
        ComWorkshop workshop = new ComWorkshop();
        BeanUtils.copyProperties(vo, workshop);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            workshop.setProductionLineConstructionT( StringUtils.hasText ( vo.getProductionLineConstructionT() ) ?
                    sdf.parse(vo.getProductionLineConstructionT()) : null);
        } catch (ParseException e) {
            log.error("日期解析失败：" + e.getMessage());
        }
        boolean save = save(workshop);
        attachmentService.saveWholeAttachmentRel(vo.getAttachmentIds(), workshop.getId(), AttModuleEnums.WORKSHOP.getCode());
        attachmentService.saveOnePubAttachmentRel ( vo.getFloorPlan(), workshop.getId(), AttModuleEnums.FLOOR_PLAN.getCode() );
        attachmentService.saveOnePubAttachmentRel ( vo.getScene (), workshop.getId(), AttModuleEnums.SCENE.getCode() );
        attachmentService.saveOnePubAttachmentRel ( vo.getEiaChapter (), workshop.getId(), AttModuleEnums.EIA_CHAPTER.getCode() );
        dataHistoryService.savePubDataHistory(workshop.getId(), vo , PubDataHistoryTypeEnum.INSERT.getCode () );
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateWorkshop(ComWorkshopVO vo) {
        ComWorkshop workshop = new ComWorkshop();
        BeanUtils.copyProperties(vo, workshop);
        if (StringUtils.hasText(vo.getProductionLineConstructionT())){
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                workshop.setProductionLineConstructionT(sdf.parse(vo.getProductionLineConstructionT()));
            } catch (ParseException e) {
                log.error("日期解析失败：" + e.getMessage());
            }
        }
        if ( vo.getAttachmentIds() != null ) {
            attachmentRelService.remove(new LambdaQueryWrapper<PubAttachmentRel>()
                    .eq(PubAttachmentRel::getStorePath, AttModuleEnums.WORKSHOP.getCode())
                    .eq(PubAttachmentRel::getRelationId, workshop.getId()));
            attachmentService.saveWholeAttachmentRel(vo.getAttachmentIds(), workshop.getId(), AttModuleEnums.WORKSHOP.getCode());
        }
        if ( ! ObjectUtils.isEmpty ( vo.getFloorPlan () ) ) {
            attachmentRelService.remove(new LambdaQueryWrapper<PubAttachmentRel>()
                    .eq(PubAttachmentRel::getStorePath, AttModuleEnums.FLOOR_PLAN.getCode())
                    .eq(PubAttachmentRel::getRelationId, workshop.getId()));
            attachmentService.saveOnePubAttachmentRel ( vo.getFloorPlan(), workshop.getId(), AttModuleEnums.FLOOR_PLAN.getCode() );

        }
        if ( ! ObjectUtils.isEmpty ( vo.getScene () ) ) {
            attachmentRelService.remove(new LambdaQueryWrapper<PubAttachmentRel>()
                    .eq(PubAttachmentRel::getStorePath, AttModuleEnums.SCENE.getCode())
                    .eq(PubAttachmentRel::getRelationId, workshop.getId()));
            attachmentService.saveOnePubAttachmentRel ( vo.getScene (), workshop.getId(), AttModuleEnums.SCENE.getCode() );

        }
        if ( ! ObjectUtils.isEmpty ( vo.getEiaChapter () ) ) {
            attachmentRelService.remove(new LambdaQueryWrapper<PubAttachmentRel>()
                    .eq(PubAttachmentRel::getStorePath, AttModuleEnums.EIA_CHAPTER.getCode())
                    .eq(PubAttachmentRel::getRelationId, workshop.getId()));
            attachmentService.saveOnePubAttachmentRel ( vo.getEiaChapter (), workshop.getId(), AttModuleEnums.EIA_CHAPTER.getCode() );

        }
        dataHistoryService.savePubDataHistory(workshop.getId(), vo , PubDataHistoryTypeEnum.UPDATE.getCode () );

        return this.updateById(workshop);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteWorkshop(String id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteWorkshop(List<String> ids) {
        return this.removeByIds(ids);
    }

    @Override
    public List < ComWorkshopVO > changelogList ( String id ) {

        List < PubDataHistory > workShopDataHistoryList =dataHistoryService.list ( new LambdaQueryWrapper < PubDataHistory >()
                .eq(PubDataHistory::getBId, id)
                .orderByDesc(PubDataHistory::getVersion)
        );

        List < ComWorkshopVO > workshopVOList = new ArrayList <> ();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日");

        for ( int i = workShopDataHistoryList.size () - 1; i >= 0 ; i-- ) {
            PubDataHistory pubDataHistory = workShopDataHistoryList.get ( i );
            if ( PubDataHistoryTypeEnum.INSERT.getCode ().equals ( pubDataHistory.getType () ) ) {
                ComWorkshopVO comWorkshopVO = JSONObject.parseObject ( pubDataHistory.getContent (), ComWorkshopVO.class );
                comWorkshopVO.setType ( PubDataHistoryTypeEnum.getDesc ( pubDataHistory.getType () ) );
                comWorkshopVO.setCreateTime(sdf.format(pubDataHistory.getCreateTime ()));
                workshopVOList.add ( comWorkshopVO );
            }else {
                PubDataHistory oldHistory = workShopDataHistoryList.get ( i + 1  );
                ComWorkshopVO comWorkshopVO = dataHistoryService.dataHistoryHandle
                        ( oldHistory.getContent (), pubDataHistory.getContent () ,  ComWorkshopVO.class );
                if ( comWorkshopVO == null ) {
                    continue;
                }
                comWorkshopVO.setType ( PubDataHistoryTypeEnum.getDesc ( pubDataHistory.getType () ) );
                comWorkshopVO.setCreateTime(sdf.format(pubDataHistory.getCreateTime ()));
                workshopVOList.add ( comWorkshopVO );
            }
        }

        return workshopVOList;
    }

    @Override
    public List<ComWorkshop> getDropdowMenu(String companyId) {
        LambdaQueryWrapper<ComWorkshop> comWorkshopLambdaQueryWrapper=new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty ( companyId ) ) {
            comWorkshopLambdaQueryWrapper.eq(ComWorkshop::getCompanyId, companyId);
        }
        return this.list(comWorkshopLambdaQueryWrapper);
    }
}




